<?php

namespace app\admin\controller\mycurrency\lease;

use app\admin\model\mycurrency\device\Device;
use app\admin\model\mycurrency\device\Lattice;
use app\common\controller\Backend;
use app\common\job\ChapterOrder;
use app\common\model\mycurrency\LeaseOrder;
use app\common\model\mycurrency\LeaseOrderDevice;
use app\common\model\mycurrency\LeaseOrderPay;
use app\common\model\mycurrency\Pay;
use app\common\model\WechatChapterOrder;
use think\Loader;

/**
 * 租赁-租赁订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\mycurrency\lease\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\mycurrency\lease\Order;
        $this->view->assign("strategyTypesList", $this->model->getStrategyTypesList());
        $this->view->assign("useStatusList", $this->model->getUseStatusList());
        $this->view->assign("cancellTypeList", $this->model->getCancellTypeList());
        $this->view->assign("payStatusList", $this->model->getPayStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with([
                        'user',
                        'deposit',
                        'strategy',
                        'package',
//                        'orderdevice.device',
//                        'order_device.lattice',
                        'store',
                        'pay',
                    ])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
//            ->buildSql();
//            dump($list);die;
            foreach ($list as $row) {
                if ($row['use_status'] == LeaseOrder::USE_STATUS_JINXINGZHONG){
                    if ($row['orderdevice']['status'] == LeaseOrderDevice::STATUS_ZULINZHONG){//租赁中
                        $row['use_status'] = 402;
                    }elseif ($row['orderdevice']['status'] == LeaseOrderDevice::STATUS_GUIHUANZHONG){//使用中
                        $row['use_status'] = 404;
                    }
                }
                $row['chapter_sn'] = $row['transaction_id'] = $row['refund_id'] = '';
                if($row['credit_id']){
                    $chapter = WechatChapterOrder::where(['lease_order_id'=>$row['id']])->find();
                    if($chapter){
                        $row['chapter_sn'] = $chapter['out_order_no'];//微信免押号
                    }
                }
                if($row['deposit_id']){
                    $deposit = \app\admin\model\mycurrency\lease\Deposit::where(['id'=>$row['deposit_id']])->find();
                    if($deposit){
                        $pay = Pay::where(['lease_deposit_id'=>$deposit['id'],'status'=>2])->find();
                        if($pay){
                            $row['refund_id'] = $pay['refund_id'];
                            $row['transaction_id'] = $pay['transaction_id'];
                        }
                    }
                }
                $order_device = \app\admin\model\mycurrency\lease\Orderdevice::where(['lease_order_id'=>$row['id']])->find();
                if($order_device){
                    $row['device_number'] = Device::where(['id'=>$order_device['device_id']])->value('number');
                    $row['device_title'] = Device::where(['id'=>$order_device['device_id']])->value('title');
                    $row['lattice_number'] = Lattice::where(['id'=>$order_device['device_lattice_id']])->value('number');
                }
                $row->visible(['id','sn','chapter_sn','device_number','device_title','lattice_number','transaction_id','refund_id','strategy_types','strategy_duration','strategy_unit_price','limit_start_time','limit_end_time','strategy_free_duration','strategy_free_frequency','strategy_free_cycle','strategy_overtime_money','strategy_overtime_company','lease_time','return_time','overtime_duration','rent_fee','overtime_fee','paymen_required','paid_dlready','use_status','cancell_type','pay_status','createtime','updatetime']);
                $row->visible(['user']);
				$row->getRelation('user')->visible(['nickname','mobile']);
				$row->visible(['deposit']);
				$row->getRelation('deposit')->visible(['id']);
				$row->visible(['strategy']);
				$row->getRelation('strategy')->visible(['title']);
				$row->visible(['package']);
				$row->getRelation('package')->visible(['title']);
                $row->visible(['orderdevice']);
                $row->visible(['order_device']);
//                $row->getRelation('orderdevice')->visible(['id','device_id','device_lattice_id','use_start_time','use_end_time','status','cancel_type']);
//                $row->orderdevice->device;
//                $row->order_device->lattice;
                $row->visible(['store']);
                $row->getRelation('store')->visible(['store_name']);
                $row->visible(['pay']);
                $row->getRelation('pay')->visible(['sn']);

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 0);
        $limit = $limit ?: 999999;
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        //处理设备编号数据
        if(isset($filter['device_number']) && !empty($filter['device_number'])){
            $device_id = Device::where(['number'=>$filter['device_number']])->value('id');
            if($device_id){
                $orderdevice = \app\admin\model\mycurrency\lease\Orderdevice::where(['device_id'=>$device_id])->select();
                foreach ($orderdevice as $value){
                    $order_ids[] = $value['lease_order_id'];
                }
            }
            unset($filter['device_number']);
        }
        if(!empty($order_ids)){
            $filter['id'] = $order_ids;
            $op['id'] = 'IN';
        }
        //处理微信支付单号
        if(isset($filter['transaction_id']) && !empty($filter['transaction_id'])){
            $pay = Pay::where(['transaction_id'=>$filter['transaction_id']])->find();
            if($pay){
                $deposit = \app\admin\model\mycurrency\lease\Deposit::where(['id'=>$pay['lease_deposit_id']])->find();
            }
            unset($filter['transaction_id']);
        }

        //处理退款单号
        if(isset($filter['refund_id']) && !empty($filter['refund_id'])){
            $pay = Pay::where(['refund_id'=>$filter['refund_id']])->find();
            if($pay){
                $deposit = \app\admin\model\mycurrency\lease\Deposit::where(['id'=>$pay['lease_deposit_id']])->find();
            }
            unset($filter['refund_id']);
        }
        if(!empty($deposit)){
            $filter['deposit_id'] = $deposit['id'];
        }
        //处理免押单号
        if(isset($filter['chapter_sn']) && !empty($filter['chapter_sn'])){
            $chapter = WechatChapterOrder::where(['out_order_no'=>$filter['chapter_sn']])->find();

            unset($filter['chapter_sn']);
        }
        if(!empty($chapter)){
            $filter['id'] = $chapter['lease_order_id'];
        }
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }

            $sym = $op[$k] ?? '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;

            $sym = strtoupper($op[$k] ?? $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
                            return $v != '' && $v !== false && $v !== null;
                        })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias)
                        && !empty($this->model) && $this->relationSearch) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }

        if (!empty($this->model)) {
            $this->model->alias($alias);
        }

        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }

}
